
import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, Typography, Flex, Space, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { apiSysDictSelect } from '../../services/common';
import { apiPermissionList, apiPermissionRemove, apiPermissionDownload } from '../../services/permissionManager';
import { download, transformArray } from '../../utils/commonUtil';
import EditModal from './Components/EditModal';
import DeleteConfirm from '../Components/DeleteConfirm';
import { SYSCODE, CONFIG_ITEM_KEYS } from '../../utils/constant';

const { Title } = Typography;
const PermissionManagement = () => {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // list 页面数据
  const [dataList, setDataList] = useState();
  // 下拉框数据
  const [buList, setBuList] = useState([]);
  const [campRoleList, setCampRoleList] = useState([]);
  const [roleList, setRoleList] = useState([]);
  const [openDrawer, setOpenDrawer] = useState(false);
  const [recordData, setRecordData] = useState({});
  const [editType, setEditType] = useState('');
  const { BU, CAMP_ROLE, SYS_ROLE } = CONFIG_ITEM_KEYS;

  const detailClickHandle = (record, type) => {
    setRecordData(record);
    setOpenDrawer(true);
    setEditType(type);
  };
  const deleteClickHandle = (record) => {
    DeleteConfirm({
      t,
      onOk () {
        apiPermissionRemove({ id: record.userId }).then((res) => {
          if (res?.data?.code === 200) {
            queryList();
          }
        });
      }
    });
  };
  const columns = [
    {
      title: t('common.email'),
      dataIndex: 'userEmail',
      width: 200,
      align: 'center'
    },
    {
      title: t('permissionManagner.campRole'),
      dataIndex: 'userCampRole',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.module'),
      dataIndex: 'userModule',
      width: 100,
      align: 'center'
    },
    // {
    //   title: t('common.bu'),
    //   dataIndex: 'buType',
    //   width: 100,
    //   align: 'center'
    // },
    {
      title: t('common.userPermission'),
      dataIndex: 'userPermission',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.createdBy'),
      dataIndex: 'createdBy',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.createTime'),
      dataIndex: 'createdTime',
      width: 110,
      align: 'center'
    },
    {
      title: t('common.updateTime'),
      dataIndex: 'updatedTime',
      width: 110,
      align: 'center'
    },
    {
      title: ' ',
      dataIndex: 'operate',
      width: 200,
      align: 'center',
      render: (_, record) => (
        <Space size={2}>
          <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, 'view')}>{t('common.view')}</Button>
          <Button
            disabled={record?.userCampRole?.includes('-Admin')}
            type="link" className='blue' size='small' onClick={() => detailClickHandle(record, 'edit')}>{t('common.edit')}</Button>
          <Button
            disabled={record?.userCampRole?.includes('-Admin')}
            type="link" className='red' size='small' onClick={() => deleteClickHandle(record)}>{t('common.delPermission')}</Button>
        </Space>
      ),
    }
  ];
  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData?.buTypes,
      campRoles: formData?.campRoles,
      createdBy: formData?.createdBy,
      userRoles: formData?.userRoles,
    };
    return params;
  };
  const serach = () => {
    setCurrentPage(1);
    queryList(1);
  };
  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    apiPermissionList(params).then((res) => {
      if (res?.data?.code === 200) {
        setDataList(res?.data?.data?.items);
        setTotalPage(res?.data?.data?.total);
      }
    });
  };
  // 调用下拉框api
  const apiSelectAsync = async () => {
    const paramsBu = {
      sysCode: SYSCODE,
      dictCodes: [BU, CAMP_ROLE, SYS_ROLE]
    };
    const { data } = await apiSysDictSelect(paramsBu);
    setBuList(transformArray(data?.data?.[BU]));
    setCampRoleList(transformArray(data?.data?.[CAMP_ROLE]));
    setRoleList(transformArray(data?.data?.[SYS_ROLE]));
  };

  useEffect(() => {
    // 正式数据
    queryList();
    // 调用下拉框api
    apiSelectAsync();
  }, [])

  return (
    <>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('layout.permissionManagement')}</Title>
        </Flex>
      </div>
      <div className='page-content-wrap'>
        <Form form={form} className='filter-wrap'>
          <Flex align='center' gap="middle">
            <Form.Item name="buTypes"
              label={t('common.bu')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={buList} />
            </Form.Item>
            <Form.Item name="campRoles"
              label={t('permissionManagner.campRole')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={campRoleList} />
            </Form.Item>
            <Form.Item name="userRoles"
              label={t('common.role')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={roleList} />
            </Form.Item>
            <Form.Item name="createdBy"
              label={t('common.createdBy')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Input placeholder={t('common.pleaseEnter')} />
            </Form.Item>
            <Button
              className='search-btn'
              type="primary"
              onClick={serach}
              icon={<SearchOutlined style={{ fontSize: 20 }} />}
            />
          </Flex>
        </Form>
        <Table
          columns={columns}
          dataSource={dataList}
          size="small"
          rowKey="userId"
          pagination={{
            total: totalPage,
            current: currentPage,
            pageSize: pageSize,
            onChange: (_crrentPage, _pageSize) => {
              setCurrentPage(_crrentPage);
              setPageSize(_pageSize);
              queryList(_crrentPage, _pageSize);
            },
            pageSizeOptions: [10, 20, 50],
            showSizeChanger: true,
            showTotal: (total) => {
              return `Total ${total} items`;
            },
          }}
        />
      </div>
      {
        openDrawer &&
        <EditModal
          openDrawer={openDrawer}
          setOpenDrawer={setOpenDrawer}
          editSucessFn={() => { queryList() }}
          editType={editType}
          recordData={recordData}
        />
      }
    </>
  )
};

export default PermissionManagement;
